var sys_toolbar = ".app_toolbar";

var cache = {
		  username			: null
		, client			: null
		, country			: null
		, default_client	: null
		, check_employee	: true
		, refresh		: function(){
				if (!cache.default_client){
					cache.default_client = null;
				}
				var request = {
						  ajax_url		: "./lookup_tables.php"
						, server_call	: "refresh_cache"
					};

				get_server_data(request, function(data){
					for(var key in data)
						cache[key] = data[key];

					if (!cache.default_client){
						alert("This might be your first time on the site.\r\nYou are being re-directed to the client screen to create a profile for you to be linked to.");
						edit_clients.type = "create";
						edit_clients.eventName = null;
						panel_list["home_page"].show();
						$().lookup_form(edit_clients, function(data){
							hide_title();
							//IF THERE IS NO DEFAULT CLIENT THEN WE NEED TO TRY AND SWITCH TO IT
							//TO DO THIS WE DO A ADMINISTRATOR CHECK-STATUS. IT WILL THEN TRIGGER
							//ALL THE NECESSARY FUNCTIONS
							//panel_list["administrators"].check_status();
							load_active_clients();

						});
					} else if (cache.members && cache.members.length <= 0 && cache.check_employee == true){
						cache.check_employee = false;
						var ret = confirm("No employees was detected.\r\nDo you want to import some employees");
						if (true == ret){
							obj = $.extend(true, {}, edit_employee);
							obj.server_call = obj.server_call_import;
							obj.event_name = null; //FORCE IT TO POP UP IMMEDIATELY
							$().import_data(obj);
						}
					}
				});
			}

		, get_item		: function(cache_item, key, value){
			var result = null;
			if (typeof value == "undefined") value = "name";
			if (!this[cache_item]) return null;

			$(this[cache_item]).each(function(){
				if (this.id == key) result = this[value];
			});

			return result;
		}
		
		, field_value : function(field, value, options){
			if (typeof options == "undefined") options = {};
			var result = value;

			switch(field.data_type){
				case "boolean":
					result = (value == 1 ? "Y" : "");
					break;
			}

			if (typeof options.ajax_url === "undefined" || options.ajax_url == null || $.trim(options.ajax_url) == ""){
				//WITH NO URL, IT MEANS WE NEED TO TRANSLATE THE SELECTED ID INTO A NAME
				var fk = field.foreign_key;
				if (fk){ //JUST IN-CASE THE FOREIGN KEY WAS NOT SET
					if (fk.sql_table in this){
						var data = this[fk.sql_table];
						$(data).each(function(){
							if ((fk.value in this) && (this[fk.key] == value)){
								result = this[fk.value];
							}
						});
					} else {
						console.log("table not found -> "+fk.sql_table);
					}
				}
			}
			
			if (result && typeof result === "string") result = result.replace(/(\n)/g, "<br/>");
			if (result == null) result = "";
			return result;
		}
	};

var system_message = null;

function set_title(message, is_blocking){
	if (typeof is_blocking == "undefined") is_blocking = true;
	$.blockUI({
			message: message,
			showOverlay: is_blocking,
			theme: true,
			css: {
				'-webkit-border-radius'		: '10px',
				'-moz-border-radius'		: '10px',
				'-webkit-border-radius'		: '10px',
				'border-radius'				: '10px',
				opacity						: 0.6 ,
				"left"						: "40%",
				"top"						: "50%"
			}
		});
}

function hide_title(){ $.unblockUI(); }

function show_feedback(msg){
	var fbp = $(".feedback_panel");

	fbp.find("h1").html(msg);
	fbp.show({"effect": "blind"});
	setTimeout(function(){
		fbp.hide({"effect": "blind"});
	}, 1500);
}



//THIS DOES ALL THE AJAX STUFF FOR THIS WINDOW
function get_server_data(request, _callback) {
	var form_data = "";

	if (typeof request == "undefined") {alert("No request options was specified"); return;}

	request.created_by		= cache.username;
	request.client			= cache.default_client;

	var data_type = "text";
	if (request.raw_data == true) data_type = "html";
	result = null;
	if (typeof request.async == "undefined") request.async = true;
	$.ajax({
			  type				: "POST"
			, cache				: false
			, async				: request.async
			, dataType			: data_type
			, url				: request.ajax_url
			, data				: "object="+($.toJSON(request))
			, processData		: false
			, success			: function(data){
					try{
						if (request.raw_data == true){
							if (_callback) _callback(data);
							hide_title();
							return;
						}

						result = $.parseJSON(data);

						if (typeof result.result_code != "undefined"){
							result.result_code = parseFloat(result.result_code);
						}

						if (result.result_code && result.result_code != 0){
							if (result.result_code == -999){
								for (index = 0; index < panel_list.length; index++) {
									$(panel_list[index][1]).is_loaded = false;
								}

								alert(result.result_message);
								window.location = "../index.php";
								hide_title();
								return;
							}
							alert(result.result_message);

						}
						else if (typeof result.result_code == "undefined"){
							alert("Error with response:\r\n"+obj.responseText);

						}
						else{
							if (_callback){
								_callback(result.result_data);
							}
						}


					}
					catch(e){
						alert("Unexpected server result:\r\n"+e+"\r\nURL: "+request.ajax_url +"\r\n"+request.server_call+"\r\n\r\n"+data);
					}

					hide_title();
			}
			, error			: function(e){alert("ERROR: "+ e);hide_title();}
			, statusCode	: {
						404: function() {alert("page not found");hide_title();}
				}
	})
	.done(function(){
		if (request.ondone) request.ondone();
		hide_title();
	});
}


//END OF AJAX STUFF FOR THIS WINDOW

function update_table_format(table){
	table = $(table);
	if (table.hasClass("has-stripes"))
		table.find("tbody tr:odd").addClass("table-stripe");

	var thead = table.children("thead");
	if (thead){
		thead.addClass("ui-widget ui-widget-header");
	}
	var tbody = table.children("tbody");
	if (tbody){
		tbody.addClass("ui-widget");
	}

	tbody.find("tr")
		.hover(
			function(){
				$(this).addClass("ui-state-hover");
				$(this).css("cursor", "pointer");
			}
			, function(){
				$(this).removeClass("ui-state-hover");

				$(this).css("cursor", "default");
			}
		);
}

function set_hover(el){
	$(el)
		.unbind("hover")
		.hover(
			function(){
				$(this).addClass("ui-state-hover");
				$(this).css("cursor", "pointer");
			}
			, function(){
				$(this).removeClass("ui-state-hover");

				$(this).css("cursor", "default");
			}
		);
}

function set_date_field(field){
	$(field).datepicker({dateFormat:"dd MM yy"});
}

function set_datetime_field(field){
	$(field).datetimepicker({dateFormat:"dd MM yy"});
}

function in_array(obj, arr_list){
	//console.log("trying to find: "+obj);
	//DOES NOT DEAL WITH NESTED ARRAYS.....NOT OF INTEREST IN MY PROJECT.
	for(var index = 0; index < arr_list.length; index++){
		var item = arr_list[index];

		if (typeof(obj) === typeof(item)){
			var same = true;	//ASSUME IT IS THE SAME

			for(key in obj){
				if (typeof(item[key]) === "undefined") {
					same = false;
				} else if (typeof(item[key]) !== typeof(obj[key])) {
					same = false;
				} else if (typeof(item[key]) === "object"){
					//TO BE IMPLEMENTED.
				} else if (item[key] !== obj[key]) {
					same = false;
				}
			}

			if (same == true) return true;
		}
	}

	return false;
}

Date.createFromMySql = function(mysql_string, date_only){
	if(typeof mysql_string === 'string' && mysql_string.length >= 10){
		var t = mysql_string.split(/[- :]/);
		//when t[3], t[4] and t[5] are missing they defaults to zero

		if (date_only && date_only == true)
			return new Date(t[0], t[1] - 1, t[2], 0, 0, 0);
		else
			return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
	}

   return null;
}

Date.createFromFirebird = function(mysql_string, date_only){
	if(typeof mysql_string === 'string' && mysql_string.length >= 10){
		var t = mysql_string.split(/[- :]/);
		//when t[3], t[4] and t[5] are missing they defaults to zero

		if (date_only && date_only == true)
			return new Date(t[0], t[1] - 1, t[2], 0, 0, 0);
		else
			return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
	}

	return null;
}
